#     TextLocutor
#     Copyright (C) 2009  Jose Ignacio Naranjo Hernandez (joseignacio.naranjo@gmail.com)

#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.

#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.

#     You should have received a copy of the GNU Affero General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.

import urllib, urllib2, httplib2
import time
from BeautifulSoup import BeautifulSoup
from xml.dom.minidom import Document

gbeep_url = "http://localhost:8080"
#gbeep_url = "http://textlocutor.appspot.com"
cgi_teams = "/football_scores/fixtures/"

countries = {1:'ARGENTINA',
             4:'AUSTRALIA',
             5:'AUSTRIA',
             6:'BELARUS',
             7:'BELGIUM',
             8:'BRAZIL',
             9:'BULGARIA',
             10:'CHILE',
             11:'CHINA',
             12:'COLOMBIA',
             13:'COSTA RICA',
             14:'CROATIA',
             15:'CYPRUS',
             16:'CZECH REPUBLIC',
             17:'DENMARK',
             18:'ECUADOR',
             19:'ENGLAND',
             20:'ESTONIA',
             22:'FINLAND',
             23:'FRANCE',
             25:'GERMANY',
             26:'GREECE',
             27:'HOLLAND',
             28:'HUNGARY',
             29:'ICELAND',
             31:'ISRAEL',
             32:'ITALY',
             33:'JAPAN',
             34:'LATVIA',
             35:'LITHUANIA',
             37:'MEXICO',
             40:'NORWAY',
             42:'PARAGUAY',
             43:'PERU',
             44:'POLAND',
             45:'PORTUGAL',
             46:'REP. OF IRELAND',
             47:'ROMANIA',
             48:'RUSSIA',
             49:'SCANDINAVIA',
             50:'SCOTLAND',
             51:'SERBIA',
             52:'SERBIA & MONTENEGRO',
             53:'SINGAPORE',
             54:'SLOVAKIA',
             55:'SLOVENIA',
             56:'SOUTH AFRICA',
             58:'SOUTH KOREA',
             59:'SPAIN',
             60:'SWENDEN',
             61:'SWITZERLAND',
             62:'TURKEY',
             63:'UKRAINE',
             64:'URUGUAY',
             65:'USA',
             66:'VENEZUELA',
             67:'WALES'}
class Gatherer:  
    def __init__(self):
        pass

    def _getLeagues(self, pos):
        page = urllib.urlopen('http://www.xscores.com/LiveScore.do?state=promptSoccerTable&sport=1&table=LEAGUE&country=%s&season=0' % pos)
        soup = BeautifulSoup(page.read())
        try:
            soup_leagues = soup.findAll(name='select', attrs={'name': 'league'})[0].findAll('option')
        except IndexError:
            return []

        leagues = []
        for league in soup_leagues:
            if league.string == 'NO LEAGUES':
                return []
            leagues.append(league.string)
        return leagues

    def _getCups(self, pos):
        page = urllib.urlopen('http://www.xscores.com/LiveScore.do?state=promptSoccerTable&sport=1&table=CUP&country=%s' % pos)
        soup = BeautifulSoup(page.read())
        try:
            soup_cups = soup.findAll(name='select', attrs={'name': 'league'})[0].findAll('option')
        except IndexError:
            return []

        cups = []
        for cup in soup_cups:
            if cup.string == 'NO CUPS':
                return []
            cups.append(cup.string)
        return cups

    def _getTeams(self, pos_country, pos_league, table):
        page = urllib.urlopen('http://www.xscores.com/LiveScore.do?state=promptSoccerTable&sport=1&country=%s&table=%s&league=%s' % (pos_country, table, pos_league))
        soup = BeautifulSoup(page.read())
        try:
            soup_teams = soup.findAll(name='table', attrs={'class': 'basic'})[0].findAll('a')
        except IndexError:
            return []

        teams = []
        for team in soup_teams:
            if team.string == 'NO TEAMS':
                return []
            teams.append(team.string)
        return teams
        
    def getCountryFixtures(self, pos, name):
        # Create the minidom document
        
        leagues = self._getLeagues(pos)
        cups = self._getCups(pos)
        if leagues != []:
            doc = Document()
            country = doc.createElement('country')
            country.setAttribute('id', (' '.join([n.capitalize() for n in name.split(' ')])))
            doc.appendChild(country)
        else:
            return None
        
        teams_b = False
        for i in range(len(leagues)):
            teams = self._getTeams(pos, i, 'LEAGUE')

            if teams != []:
                teams_b = True
                league = doc.createElement('league')
                league.setAttribute('id', (' '.join([n.capitalize() for n in leagues[i].split(' ')])))
                country.appendChild(league)
            
                for j in range(len(teams)):
                    team = doc.createElement('team')
                    t = ''
                    team_str = doc.createTextNode(' '.join([n.capitalize() for n in teams[j].split(' ')]))
                    team.appendChild(team_str)
                    league.appendChild(team)
        if not teams_b:
            return None 
        # Print our newly created XML
        return doc.toxml()

import AEConnector

if __name__ == "__main__":
    connector = AEConnector.AEConnector(dev_server=True)
    g = Gatherer()

    for k, v in countries.items():
        doc = g.getCountryFixtures(k, v)
        if doc:
            print doc
            url = gbeep_url + cgi_teams
            sent = False
            while not sent:
                try:
                    response = connector.sendRequest(url, doc)
                    sent = True
                except urllib2.HTTPError, e:
                    print e
                    time.sleep(10)
